package com.paul.sys.util;


import com.paul.sys.model.Ptstaff;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by yingg_000 on 2015/9/10.
 */
public class SessionFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        String reuestURl = request.getRequestURI();






        if (reuestURl.equals(request.getContextPath() + "/")) {
            //返回公共首页
            response.sendRedirect(request.getContextPath() + "/back/loginPage.do");
            return;
        } else {
            if (reuestURl.indexOf("back/loginPage.do") != -1 || reuestURl.indexOf("back/login.do") != -1||
                    reuestURl.indexOf("back/session.do")!=-1) {

            } else {
                if (reuestURl.indexOf("onpublic") == -1) {
                    //表示属于登陆超时拦截
                    if(request.getSession() == null){
                       // MapUtil.put("outtime",false);
                        response.sendRedirect(request.getContextPath() + "/back/session.do");
                        return;
                    }
                    Ptstaff user = CommSession.getUser(request);
                    if (user == null) {
                        response.sendRedirect(request.getContextPath() + "/back/session.do");
                        return;
                    }
                    //判断是否是菜单url
                    if(reuestURl.indexOf("ismenu")!=-1){
                        List menus = CommSession.getMenu(request);

                        if(menus==null||!menus.contains(reuestURl)){
                            response.sendRedirect(request.getContextPath() + "/back/session.do");
                            return ;
                        }
                    }
//                    if(CommSession.getMenu(request)==null){
//
//                    }
//                    if(!CommSession.getMenu(request).contains(reuestURl)){
//                        response.sendRedirect(request.getContextPath()+"/back/error.do");
//                        return;
//                    }

                }

            }
        }


        chain.doFilter(req, res);
    }

    @Override
    public void destroy() {

    }


}
